package de.ohmhochschule.bme;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;


/**
 * This is the Starting Activity.
 * Creates a WebView and loads it with a local webpage.  Notice, that it
 * also loads stylesheets and images from the local storage (/res/raw/).
 */
public class KathyActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setTitle("Kathy");
		WebView webView = new WebView(this);
		webView.setWebViewClient( new KathyWebViewClient() );
		String html = readFile();
		webView.loadDataWithBaseURL("file:///android_res/raw/", html, 
		                            "text/html", "UTF-8", null);
		setContentView(webView);
	}
	
	/**
	 * This reads the file index.html from the /res/raw/ folder.
	 * @return a web page as HTML
	 */
	private String readFile() {
		StringBuffer sb = new StringBuffer();
		try {
			InputStream htmlStream = getResources().openRawResource(R.raw.index);
			BufferedReader is = new BufferedReader(new InputStreamReader(htmlStream, "UTF8"));
			String line;
			while ((line = is.readLine()) != null) {
				sb.append(line);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}

	/**
	 * This makes sure that you are not opening an external browser when clicking on links.
	 * Depending on the link, it will start with a different page in the DetailActivity. 
	 * @see android-sdk/docs/resources/tutorials/views/hello-webview.html
	 */
	private class KathyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.i("test-","url: "+url);
			if ( url.startsWith("int:") ) {
				Intent intent = new Intent( KathyActivity.this, DetailActivity.class );
				intent.putExtra(DetailActivity.STARTING_PAGE, Integer.parseInt( url.substring(4) ));
				startActivity(intent);		
			}
			return true;
		}		
	}	
}